package com.rk.admin.config;
import com.rk.admin.domain.User;
import com.rk.admin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

//认证类，该类中有shiro提供的认证方法和授权方法，跟数据库的桥梁
public class MyRealm extends AuthorizingRealm {


    @Autowired
    private UserService usersService;

    //处理用户登录的，当UserController 的login接口调用 subject.login(token);
    //获得用户认证信息，其实从数据库中查询用户信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username =(String)token.getPrincipal();//获得当前登录用户名称
        //通过用户名查询用户  校验用户名
        User user=this.login(username);
        //封装到AuthenticationInfo类中从数据库中查询出来的用户信息 用户名正常
        AuthenticationInfo  info=null;
        if(user!=null){
            //查询出来用户信息放到session对象中
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            User user123 =(User) SecurityUtils.getSubject().getSession().getAttribute("user");
            System.out.println("登录的时候存入的user:"+user123);

            //校验密码
            info=new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),
                    super.getName());
        }
        return info;
    }


    private User login(String username) {
        return usersService.login(username);
    }

    //授权方法，处理角色权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
